package mobi.yuanshen.controller;

import lombok.extern.slf4j.Slf4j;
import mobi.yuanshen.anno.Log;
import mobi.yuanshen.pojo.Dept;
import mobi.yuanshen.utils.Result;
import mobi.yuanshen.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    /**
     * 查询全部的部门信息
     * @return
     */
    @GetMapping
    public Result list () {
        log.info("\n查询全部数据");
        List<Dept> deptList = deptService.list();
        return Result.success(deptList);
    }

    /**
     * 根据部门id删除部门
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Log
    public Result delById (@PathVariable Integer id) throws Exception {
        log.info("删除部门:{}",id);
        deptService.delById(id);
        return Result.success();
    }

    /**
     * 新增部门
     * @param dept
     * @return
     */
    @PostMapping
    @Log
    public Result addDept (@RequestBody Dept dept) {
        log.info("新增部门:{}",dept.getName());
        deptService.add(dept);
        return Result.success();
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result queryById (@PathVariable Integer id) {
        Dept dept =  deptService.queryById (id);
        if (dept == null) {
            return Result.error("部门不存在");
        }
        return Result.success(dept);
    }

    /**
     * 修改部门
     */
    @PutMapping
    @Log
    public Result updateDept (@RequestBody Dept dept) {
        Integer count =  deptService.updateDept(dept);
        if (count == 0) {
            return Result.error("没有该部门的信息");
        }
        log.info("已经成功将部门{}的信息变更为{}",dept.getId(),dept.getName());
        return Result.success();
    }

}
